<?php

namespace App\Http\Middleware;

use App\Models\Order;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class ValidateOrderOperation
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next, string $operation): Response
    {
        $orderId = $request->route('order') ?? $request->route('orderId');
        
        if (!$orderId) {
            return $this->errorResponse('订单ID不能为空', 400);
        }

        $order = Order::find($orderId);
        
        if (!$order) {
            return $this->errorResponse('订单不存在', 404);
        }

        // 检查用户权限
        if (auth()->id() !== $order->user_id && !auth()->user()->hasRole('admin')) {
            return $this->errorResponse('无权访问此订单', 403);
        }

        // 验证操作权限
        if (!$this->validateOperation($order, $operation)) {
            return $this->errorResponse($this->getOperationErrorMessage($operation, $order), 422);
        }

        // 将订单添加到请求中，供控制器使用
        $request->merge(['validated_order' => $order]);

        return $next($request);
    }

    /**
     * 验证操作权限
     */
    protected function validateOperation(Order $order, string $operation): bool
    {
        return match($operation) {
            'cancel' => $order->canCancel(),
            'ship' => $order->canShip(),
            'deliver' => $order->canConfirmDelivery(),
            'after-sales' => $order->canApplyAfterSales(),
            'modify-address' => $order->canModifyAddress(),
            'modify-notes' => $order->canModifyNotes(),
            'refund' => $order->canRefund(),
            'reship' => $order->canReship(),
            'track' => $order->canTrackShipping(),
            'view' => true, // 查看订单总是允许的
            default => false,
        };
    }

    /**
     * 获取操作错误消息
     */
    protected function getOperationErrorMessage(string $operation, Order $order): string
    {
        $statusText = $order->status_text;
        $paymentStatusText = $order->payment_status_text;

        return match($operation) {
            'cancel' => "订单状态为「{$statusText}」，无法取消",
            'ship' => "订单状态为「{$statusText}」或支付状态为「{$paymentStatusText}」，无法发货",
            'deliver' => "订单状态为「{$statusText}」，无法确认收货",
            'after-sales' => "订单状态为「{$statusText}」或支付状态为「{$paymentStatusText}」，无法申请售后",
            'modify-address' => "订单状态为「{$statusText}」或支付状态为「{$paymentStatusText}」，无法修改地址",
            'modify-notes' => "订单状态为「{$statusText}」，无法修改备注",
            'refund' => "订单状态为「{$statusText}」或支付状态为「{$paymentStatusText}」，无法申请退款",
            'reship' => "订单状态为「{$statusText}」或支付状态为「{$paymentStatusText}」，无法重新发货",
            'track' => "订单状态为「{$statusText}」或无物流单号，无法查看物流",
            default => '无效的操作',
        };
    }

    /**
     * 返回错误响应
     */
    protected function errorResponse(string $message, int $statusCode): Response
    {
        if (request()->expectsJson()) {
            return response()->json([
                'success' => false,
                'message' => $message,
            ], $statusCode);
        }

        return redirect()->back()
            ->with('error', $message)
            ->withInput();
    }
}
